const express = require('express');
const router = express.Router();
const { query } = require('../config/database');

// 根据id获取分类详情
router.get('/', async (req, res) => {
  try {
    const { id } = req.query;
    
    if (!id) {
      return res.json({
        code: '0',
        msg: '分类ID不能为空',
        result: null
      });
    }

    // 查询主分类信息
    const categoryQuery = `
      SELECT 
        c.category_id as id,
        c.category_name as name,
        c.category_icon as picture
      FROM sys_category c 
      WHERE c.category_id = ?
    `;
    
    const categoryResult = await query(categoryQuery, [id]);
    
    if (categoryResult.length === 0) {
      return res.json({
        code: '0',
        msg: '分类不存在',
        result: null
      });
    }

    const category = {
      id: categoryResult[0].id.toString(),
      name: categoryResult[0].name,
      picture: categoryResult[0].picture
    };
    
    // 查询sys_pcc表获取子分类信息
    const childrenQuery = `
      SELECT 
        pcc_id as id,
        pcc_name as name,
        pcc_picture as picture,
        pcc_parent as parentId
      FROM sys_pcc
      WHERE pcc_parent = ?
      ORDER BY pcc_id ASC
    `;
    
    const children = await query(childrenQuery, [id]);
    
    // 为每个子分类查询商品
    for (let child of children) {
      // 转换子分类字段格式
      child.id = child.id.toString();
      child.parentId = child.parentId ? child.parentId.toString() : null;
      child.parentName = categoryResult[0].name;
      
      // 从sys_prodclass表获取商品ID
      const prodclassQuery = `
        SELECT prodclass_goods
        FROM sys_prodclass
        WHERE category_id = ? AND prodclass_children = ?
      `;
      
      const prodclassResult = await query(prodclassQuery, [id, child.id]);
      
      if (prodclassResult.length > 0 && prodclassResult[0].prodclass_goods) {
        const goodsIds = prodclassResult[0].prodclass_goods.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id)).slice(0, 10);
        
        if (goodsIds.length > 0) {
          const placeholders = goodsIds.map(() => '?').join(',');
          const goodsQuery = `
            SELECT 
              g.goods_id as id,
              g.goods_name as name,
              g.goods_desc as \`desc\`,
              g.goods_price as price,
              g.goods_picture as picture,
              g.goods_orderNum as orderNum
            FROM sys_goods g
            WHERE g.goods_id IN (${placeholders})
            ORDER BY g.goods_orderNum DESC
          `;
          
          const goods = await query(goodsQuery, goodsIds);
          // 转换商品字段格式
          child.goods = goods.map(good => ({
            id: good.id.toString(),
            name: good.name,
            desc: good.desc,
            price: parseFloat(good.price).toFixed(2),
            picture: good.picture,
            orderNum: good.orderNum
          }));
        } else {
          child.goods = [];
        }
      } else {
        child.goods = [];
      }
      
      child.categories = null;
      child.brands = null;
      child.saleProperties = null;
    }
    
    // 如果没有子分类，创建一个包含主分类商品的子分类项
    if (children.length === 0) {
      // 为主分类获取商品数据（查找 category_id 匹配且 prodclass_children 为主分类ID的记录）
      const mainProdclassQuery = `
        SELECT prodclass_goods
        FROM sys_prodclass
        WHERE category_id = ? AND prodclass_children = ?
        LIMIT 1
      `;
      
      const mainProdclassResult = await query(mainProdclassQuery, [id, id]);
      
      let goods = [];
      if (mainProdclassResult.length > 0 && mainProdclassResult[0].prodclass_goods) {
        const goodsIds = mainProdclassResult[0].prodclass_goods.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id)).slice(0, 10);
        
        if (goodsIds.length > 0) {
          const placeholders = goodsIds.map(() => '?').join(',');
          const goodsQuery = `
            SELECT 
              g.goods_id as id,
              g.goods_name as name,
              g.goods_desc as \`desc\`,
              g.goods_price as price,
              g.goods_picture as picture,
              g.goods_orderNum as orderNum
            FROM sys_goods g
            WHERE g.goods_id IN (${placeholders})
            ORDER BY g.goods_orderNum DESC
          `;
          
          const goodsResult = await query(goodsQuery, goodsIds);
          // 转换主分类商品字段格式
          goods = goodsResult.map(good => ({
            id: good.id.toString(),
            name: good.name,
            desc: good.desc,
            price: parseFloat(good.price).toFixed(2),
            picture: good.picture,
            orderNum: good.orderNum
          }));
        }
      }
      
      // 创建一个子分类项包含主分类的商品
      children.push({
        id: category.id,
        name: category.name,
        picture: category.picture,
        parentId: null,
        parentName: null,
        goods: goods,
        categories: null,
        brands: null,
        saleProperties: null
      });
    }
    
    category.children = children;
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: category
    });
  } catch (error) {
    console.error('获取分类详情失败:', error);
    res.json({
      code: '0',
      msg: '获取分类详情失败',
      result: null
    });
  }
});

// 获取二级分类列表数据
router.get('/sub/filter', async (req, res) => {
  try {
    const { id } = req.query;
    
    if (!id) {
      return res.json({
        code: '0',
        msg: '分类ID不能为空',
        result: null
      });
    }

    // 查询子分类列表
    const subCategoriesQuery = `
      SELECT 
        c.category_id as id,
        c.category_name as name,
        c.category_icon as picture
      FROM sys_category c
      WHERE c.category_parent = ?
      ORDER BY c.category_id ASC
    `;
    
    const subCategories = await query(subCategoriesQuery, [id]);
    
    // 查询品牌信息（模拟数据）
    const brands = [
      { id: '1', name: '小兔鲜', nameEn: 'rabbit-fresh', picture: '', desc: '高品质生活用品' },
      { id: '2', name: '网易严选', nameEn: 'yanxuan', picture: '', desc: '严选好物' }
    ];
    
    // 查询销售属性（模拟数据）
    const saleProperties = [
      {
        id: '1',
        name: '颜色',
        properties: [
          { id: '1', name: '红色' },
          { id: '2', name: '蓝色' },
          { id: '3', name: '绿色' }
        ]
      },
      {
        id: '2', 
        name: '尺寸',
        properties: [
          { id: '4', name: 'S' },
          { id: '5', name: 'M' },
          { id: '6', name: 'L' }
        ]
      }
    ];
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: {
        parentId: id,
        parentName: '',
        categories: subCategories,
        brands: brands,
        saleProperties: saleProperties
      }
    });
  } catch (error) {
    console.error('获取二级分类列表失败:', error);
    res.json({
      code: '0',
      msg: '获取二级分类列表失败',
      result: null
    });
  }
});

// 获取分类商品列表（POST请求）
router.post('/goods/temporary', async (req, res) => {
  try {
    const { categoryId, page = 1, pageSize = 20, sortField = 'publishTime' } = req.body;
    
    if (!categoryId) {
      return res.json({
        code: '0',
        msg: '分类ID不能为空',
        result: null
      });
    }

    const offset = (page - 1) * pageSize;
    
    // 根据排序字段确定ORDER BY子句
    let orderBy = 'g.goods_id DESC';
    switch (sortField) {
      case 'publishTime':
        orderBy = 'g.goods_id DESC';
        break;
      case 'orderNum':
        orderBy = 'g.goods_orderNum DESC';
        break;
      case 'evaluateNum':
        orderBy = 'g.goods_orderNum DESC'; // 暂时用orderNum代替
        break;
    }
    
    // 从sys_prodclass表获取所有相关的商品ID
    const prodclassQuery = `
      SELECT prodclass_goods
      FROM sys_prodclass
      WHERE category_id = ? OR prodclass_children IN (
        SELECT category_id FROM sys_category WHERE category_parent = ?
      )
    `;
    
    const prodclassResults = await query(prodclassQuery, [categoryId, categoryId]);
    
    // 收集所有商品ID
    let allGoodsIds = [];
    for (let result of prodclassResults) {
      if (result.prodclass_goods) {
        const goodsIds = result.prodclass_goods.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
        allGoodsIds = allGoodsIds.concat(goodsIds);
      }
    }
    
    // 去重
    allGoodsIds = [...new Set(allGoodsIds)];
    
    const total = allGoodsIds.length;
    
    if (allGoodsIds.length === 0) {
      return res.json({
        code: '1',
        msg: '操作成功',
        result: {
          items: [],
          counts: 0,
          pageSize: pageSize,
          page: page
        }
      });
    }
    
    // 分页处理
    const pagedGoodsIds = allGoodsIds.slice(offset, offset + pageSize);
    
    if (pagedGoodsIds.length === 0) {
      return res.json({
        code: '1',
        msg: '操作成功',
        result: {
          items: [],
          counts: total,
          pageSize: pageSize,
          page: page
        }
      });
    }
    
    // 查询商品详情
    const placeholders = pagedGoodsIds.map(() => '?').join(',');
    const goodsQuery = `
      SELECT 
        g.goods_id as id,
        g.goods_name as name,
        g.goods_desc as \`desc\`,
        g.goods_price as price,
        g.goods_picture as picture,
        g.goods_orderNum as orderNum,
        g.goods_orderNum as evaluateNum
      FROM sys_goods g
      WHERE g.goods_id IN (${placeholders})
      ORDER BY ${orderBy}
    `;
    
    const goods = await query(goodsQuery, pagedGoodsIds);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: {
        items: goods,
        counts: total,
        pageSize: pageSize,
        page: page
      }
    });
  } catch (error) {
    console.error('获取分类商品列表失败:', error);
    res.json({
      code: '0',
      msg: '获取分类商品列表失败',
      result: null
    });
  }
});

module.exports = router;